import pygame
import Image
from pygame.locals import *
import sys

import opencv
#this is important for capturing/displaying images
from opencv import highgui

from PIL import Image

from socket import *
from Tkinter import *
from select import *

def connect(host = '192.168.0.4',port = 6008):
    while True:
        try:
            print 'Attempting to connect to '+host+' at port '+str(port)+'.'
            # Make an internet socket, TCP connection mode
            s = socket(AF_INET, SOCK_STREAM)

            # Connect to localhost on port 9999
            s.connect((host,port))
            return s
        except:
            print 'Connection Failed.\n'

s = connect()

camera = highgui.cvCreateCameraCapture(1)
#help(camera)

def get_image():
    #print 'Debug 1'
    im = highgui.cvQueryFrame(camera)
    # Add the line below if you need it (Ubuntu 8.04+)
    #print 'Debug 2'
    im = opencv.cvGetMat(im)
    #convert Ipl image to PIL image
    #print 'Debug 3'
    return opencv.adaptors.Ipl2PIL(im) 

pygame.init()
#window = pygame.display.set_mode((640,480))
#pygame.display.set_caption("WebCam Demo")
#screen = pygame.display.get_surface()
fps = 30.0
while True:
    events = pygame.event.get()
    for event in events:
        if event.type == QUIT or event.type == KEYDOWN:
            sys.exit(0)
    im = get_image()
    #s.send(im.mode)
    #print(im.size)
    #s.send(str(im.size[0]))
    #s.send(str(im.size[1]))
    print len(im.tostring())
    #print im.size
    #print im.mode
    for i in range(100):
        print str(i)+":\t"+str(i*9216)+"\t"+str((i+1)*9216)
        s.send(im.tostring()[i*9216:(i+1)*9216])
    pygame.time.delay(int(1000.0/fps))

    #mode = "RGB"
    #size = (640,480)
    #data = im.tostring()
    #pg_img = pygame.image.frombuffer(data, size, mode)
    #screen.blit(pg_img, (0,0))
    #pygame.display.flip()




